package com.tanhua.api.mongo;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@Service
public class PublishApiImpl implements PublishApi {

    @Autowired
    private IdService idService;
    @Autowired
    private MongoTemplate mongoTemplate;
    //发布消息
    public String save(Publish publish) {

        // 1 保存数据到动态详情表
        publish.setId(new ObjectId());
        publish.setPid(idService.getNextId("quanzi_publish")); //设置大数据的一个字段pid
        publish.setCreated(System.currentTimeMillis()); //系统的当前毫秒值
        mongoTemplate.insert(publish,"quanzi_publish");

        // 2 保存数据到个人动态表
        Album album = new Album();
        album.setPublishId(publish.getId());
        album.setCreated(System.currentTimeMillis());
        mongoTemplate.save(album,"quanzi_album_"+publish.getUserId());

        // 3 查询好友表
        Query query = new Query(Criteria.where("userId").is(publish.getUserId()));

        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        if(CollectionUtil.isNotEmpty(friendList)){
            // 4 将数据保存到好友的时间线（好友动态）表
            for (Friend friend : friendList) {
                TimeLine timeLine = new TimeLine();
                timeLine.setPublishId(publish.getId());
                timeLine.setUserId(publish.getUserId());
                timeLine.setCreated(System.currentTimeMillis());
                mongoTemplate.save(timeLine,"quanzi_time_line_"+friend.getFriendId());
            }
        }

        return publish.getId().toString();

    }

    //我的动态
    public PageBeanVo findMyPublish(Integer page, Integer pagesize, Long userId) {
        // 根据用户的id查询自己的个人信息表 得到每一个publishId
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC,"created")); //排序
        query.skip((page-1)*pagesize).limit(pagesize); //分页
        long count = mongoTemplate.count(query, "quanzi_album_" + userId); //总条数
        ////指定查登录用户的个人动态表
        List<Album> albumList = mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);

        // 根据publishId查询自己发布的内容 动态发布表
        List<Publish> publishList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(albumList)){
            for (Album album : albumList) {
                // 根据个人动态表的publishId获取到每一个Publish动态发布对象
                Publish publish = mongoTemplate.findById(album.getPublishId(), Publish.class);
                // 我只要审核通过的内容+图片信息
                if(publish.getState()==1){
                    publishList.add(publish);
                }
            }
        }
        // 封装pageBeanVo
        PageBeanVo pageBeanVo = new PageBeanVo(page,pagesize,count,publishList);
        return pageBeanVo;
    }

    @Override
    public PageBeanVo findTimeLinePublish(Integer page, Integer pagesize, Long userId) {

        // 查询时间线表
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        long count = mongoTemplate.count(query, "quanzi_time_line_" + userId);
        List<TimeLine> timeLineList = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);

        // 根据时间线表得到publishId
        List<Publish> publishList = new ArrayList<>();
         if(CollectionUtil.isNotEmpty(timeLineList)){
             for (TimeLine timeLine : timeLineList) {
                 Publish publish = mongoTemplate.findById(timeLine.getPublishId(), Publish.class);
                 if(publish.getState()==1){
                     publishList.add(publish);
                 }
             }
         }

        // 根据publishId获取list<publish>
        PageBeanVo pageBeanVo = new PageBeanVo(page,pagesize,count,publishList);

        return pageBeanVo;
    }

    //查询推荐信息
    public PageBeanVo findRecommendPublish(Integer page, Integer pagesize, Long userId) {

        //查询的是推荐表
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        long count = mongoTemplate.count(query, "recommend_quanzi");
        List<RecommendQuanzi> recommendQuanziList = mongoTemplate.find(query, RecommendQuanzi.class, "recommend_quanzi");

        List<Publish> publishList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(recommendQuanziList)){
            for (RecommendQuanzi recommendQuanzi : recommendQuanziList) {
                Publish publish = mongoTemplate.findById(recommendQuanzi.getPublishId(), Publish.class);
                if(publish.getState()==1){
                    publishList.add(publish);
                }
            }
        }

        return new PageBeanVo(page,pagesize,count,publishList);
    }

    @Override
    public Publish findByIdtoPublish(String publishId) {
        //根据传递的publishId查询主键 获取publish对象
        return mongoTemplate.findById(new ObjectId(publishId),Publish.class);
    }

    // 查询该用户的圈子数据
    public PageBeanVo findPublish(Integer page, Integer pagesize, Long uid, Integer state) {

        Query query=new Query();
        //判断用户id和审核状态是否为空 不为空才做当前用户的条件查询    为空 做的是全查
        Criteria criteria = new Criteria();
        if(uid!=null){
            criteria.and("userId").is(uid);
        }
        if(state!=null){
            criteria.and("state").is(state);
        }
        query.addCriteria(criteria);
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);

        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        long count = mongoTemplate.count(query, Publish.class);
        return new PageBeanVo(page,pagesize,count,publishList);
    }

    @Override
    public void updateState(String publishId, Integer state) {
        Query query = new Query(Criteria.where("id").is(new ObjectId(publishId)));
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.updateFirst(query,update,Publish.class);
    }

    @Override
    public Publish findByPid(long pid) {
        Query query = new Query(Criteria.where("pid").is(pid));
        return mongoTemplate.findOne(query,Publish.class);
    }
}
